<?php

namespace app\admin\model\hotel;

use addons\epay\library\Service;
use think\Db;
use think\Log;
use think\Model;
use traits\model\SoftDelete;
use Yansongda\Pay\Pay;

class HotelOrder extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'hotel_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'pay_time_text',
        'cancel_time_text'
    ];
    

    



    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['pay_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCancelTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['cancel_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCancelTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function hotel()
    {
        return $this->belongsTo('app\admin\model\Hotel', 'hotel_id', 'hotel_id', [], 'LEFT')->setEagerlyType(0);
    }


    public function room()
    {
        return $this->belongsTo('Room', 'room_id', 'room_id', [], 'LEFT')->setEagerlyType(0);
    }


    public function refund($order_id,$realprice,$refundprice)
    {
        $order = HotelOrder::get($order_id);
        if ($order->is_refund==1)throw new \Exception('已退款');
        if ($order->pay_status==0)throw new \Exception('未支付');

        Db::startTrans();
        try {
            if ($refundprice>0&&$order->pay_type=='wechat'){
                $res = $this->refundoperate($order->order_no, 'wechat',$realprice,$refundprice);
                if (!$res){
                    Db::rollback();
                    throw new \Exception('退款失败');
                }
                $order->refund_money=$refundprice;
            }

            $order->order_status = 4;
            $order->order_status_name = '售后成功';
            $order->is_refund = 1;
            $order->salestate=3;

            $res = $order->save();
            Db::commit();
            return $res;

        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
    }

    public function refundoperate($order_sn, $paytype, $payamount,$refund)
    {
        $config = Service::getConfig($paytype);
        try {
            //$order = Order::getByOrderSn($order_sn);

            $response = Pay::wechat($config)->refund([
                'type'          => 'miniapp',
                'out_trade_no'  => $order_sn,
                'out_refund_no' => time(),
                'total_fee'     => $payamount * 100,
                'refund_fee'    => $refund * 100
            ]);

            if (!$response['result_code'] || $response['result_code'] != 'SUCCESS') {
                throw new \Exception(($response['err_code'] ?? '') . ':' . ($response['err_code_des'] ?? '未知退款错误'));
            }

        } catch (\Exception $e) {
            Log::write("[{$order_sn}]同步退款失败，失败原因：" . $e->getMessage(), 'refund');
            throw new \Exception("同步退款失败，失败原因：" . $e->getMessage());
        }

        return true;
    }

}
